<?php

namespace App\Http\Controllers;

use App\Helpers\ResponseEnum;
use App\Http\Requests\CertificationRequest;
use App\Models\Users;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;


class LoginController extends BaseController
{
    /**
     * 用户认证
     */
    public function certification(CertificationRequest $request)
    {
        $auth = session('wechat.oauth_user.default');

        if(empty($auth)){
            return redirect('/');
        }

        //$openId = 'o5T_U6LA7pYMntHSluxrlzCC5yfw';

        //$user = User::where('open_id' , $request->session()->get('openId'))->first();

        $user = User::where('open_id' , $auth->getId())->first();

        if(!empty($user->phone)){
            return $this->fail(ResponseEnum::USER_SERVICE_LOGIN_SUCCESS);
        }

        $user->phone = $request->post('mobile' , null);

        $user->name = $request->post('name' , null);

        if ($user->save()) {
            return $this->success([] , ResponseEnum::USER_SERVICE_LOGIN_SUCCESS);
        }

        return $this->fail(ResponseEnum::SERVICE_LOGIN_ERROR);

    }

    /**
     * 用户登录
     */
    public function login(Request $request , $parent = null)
    {
        $auth = session('wechat.oauth_user.default');

        //是否是扫码进入
        $parentUser = !empty($parent) ? Users::where('code', $parent)->first() : null;

        $user = Users::where('open_id', $auth->getId())->first();

        if (empty($user)) {
            $newUser = Users::create(['open_id' => $auth->getId() , 'nick_name' => $auth->getNickname(), 'avatar' => $auth->getAvatar(), 'original' => $auth ,'code' => uniqid() , 'parent_user_id' => !empty($parentUser) ? $parentUser->id : 0]);

            //判断所属上级是否为空
            if(!empty($parentUser)){
                //判断所属上级是否还有上级 如果有 并且有人同事发展了下线 则变成一级
                if(!empty($parentUser->parent_user_id) && $parentUser->parent_user_id != 0){
                    $parentUser->parent_user_id = 0;

                    $parentUser->save();
                }
            }

        } if (!empty($user) && !empty($user->phone)) {

            session(['loginUser' => ['id' => $user->id , 'openId' => $auth->getId(), 'name' => $user->name ,'nick_name' => $auth->getNickname(), 'phone' => $user->phone , 'avatar' => $auth->getAvatar(),'code' => $user->code]]);

            return redirect('goods/list');
        }

        //跳转到认证页面
        return view('login');

    }
}
